package br.com.pnfp.web.control.actions.login;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.dao.EmptyResultDataAccessException;

import br.com.pnfp.web.control.actions.DefaultAction;
import br.com.pnfp.web.control.forms.login.LoginForm;
import br.com.pnfp.web.model.dao.exceptions.SenhaInvalidaException;
import br.com.pnfp.web.model.dao.exceptions.UsuarioInativoException;
import br.com.pnfp.web.model.dao.exceptions.UsuarioInvalidoException;
import br.com.pnfp.web.model.vo.Doador;
import br.com.pnfp.web.model.vo.Usuario;

public class LoginAction extends DefaultAction {
	
	private static final Logger logger = Logger.getLogger(LoginAction.class); 
	
	public ActionForward iniciar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {		
		
		return mapping.findForward("login");
	}
	
	public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		LoginForm loginForm = (LoginForm) form;
		
		try {
			Usuario usuario = new Usuario();
			usuario.setLogin(loginForm.getUsuario());
			usuario.setSenha(loginForm.getSenha());
			Usuario vo = getUsuarioDAO().login(usuario);		
			setUsuario(request, vo);
			
			logger.info("Sucessfully logon to: " + loginForm.getUsuario());
			verificaPendencias(request);
			return mapping.findForward("home");
		} catch(EmptyResultDataAccessException exc) {
			addMessage(request, "login.usuario.invalido");
			logger.info("Invalid User to: " + loginForm.getUsuario());
		} catch(UsuarioInvalidoException exc) {
			addMessage(request, "login.usuario.invalido");
			logger.info("Invalid User to: " + loginForm.getUsuario());
		} catch (SenhaInvalidaException exc) {
			addMessage(request, "login.senha.invalida");
			logger.info("Invalid Password to: " + loginForm.getUsuario());
		} catch(UsuarioInativoException exc) {
			addMessage(request, "login.usuario.inativo");
			logger.info("Disabled User to: " + loginForm.getUsuario());
		}
		
		return mapping.findForward("login");
	}
	
	public ActionForward home(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {			
		verificaPendencias(request);
		return mapping.findForward("home");
	}
	
	public ActionForward sair(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {		
		
		logger.info("Logoff: " + getUsuario(request));
		request.getSession().invalidate();
		
		return mapping.findForward("login");
	}
	
	private void verificaPendencias(HttpServletRequest request) {
		
		if(isAdministrator(request)) {
			
			List<Doador> doadores = getDoadorDAO().consultar(new Doador(getUsuario(request)));
			
			List<Doador> pendencias = new ArrayList<Doador>();
			for(Doador doador : doadores) {
				if(doador.getEntidade() == null)
					pendencias.add(doador);
			}			
			
			if(!pendencias.isEmpty()) {
				request.setAttribute("doadores", pendencias);
			}
		}
	}
}
